package com.luo.bbs.front.webapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bbs.front.service.IAnnounceService;
import com.luo.bbs.front.webapi.mapper.AnnounceMapper;
import com.luo.bbs.front.webapi.pojo.UserLoginPrincipal;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;
import com.luo.pojo.Announce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class AnnounceServiceImpl extends ServiceImpl<AnnounceMapper, Announce> implements IAnnounceService {
    @Autowired
    private AnnounceMapper announceMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //最新公告
    @Override
    public Announce get() {
        QueryWrapper<Announce> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create").last("limit 1");
        Announce announce = announceMapper.selectOne(wrapper);
        return announce;
    }

    @Override
    public void addViews(Integer id) {
        if (id == null) {
            throw new BBSServiceException(ResponseCode.BAD_REQUEST, "参数错误");
        }
        Announce announce = announceMapper.selectById(id);
        if (announce == null) {
            throw new BBSServiceException(ResponseCode.NOT_FOUND, "不存在");
        }

        Integer userId = getUserId();
        String readViewKey = "readView:" + id;
        String value = userId  + "";
        Long add = stringRedisTemplate.boundSetOps(readViewKey).add(value);
        if (add != 0){
            announce.setReadViews(announce.getReadViews()+1);
            announceMapper.updateById(announce);
        }
    }


    public UserLoginPrincipal getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginPrincipal principal = (UserLoginPrincipal) authentication.getPrincipal();
        if (principal == null) {
            throw new BBSServiceException(ResponseCode.UNAUTHORIZED, "未登录！");
        }
        return principal;
    }

    public Integer getUserId() {
        if (getUserInfo() == null) {
            return null;
        }
        return getUserInfo().getId();
    }
}
